const fs = require('fs')
const path = require('path')
const { canDirectoryLint } = require('../../utils/index')

module.exports = {
  meta: {
    type: 'problem',
    docs: {
      description: '检查指定目录下的文件结构是否符合预期',
      category: 'Best Practices',
      recommended: false,
    },
    schema: [
      {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            root: {
              type: 'string',
            },
            includes: {
              type: 'array',
              items: {
                type: 'string',
              },
            },
            ignores: {
              type: 'array',
              items: {
                type: 'string',
              },
            },
          },
        },
      },
    ],
  },
  create(context) {
    const options = context.options[0] || {}

    if (!canDirectoryLint(context)) return {}

    const checkSrcDirectory = (config) => {
      const { root, includes, ignores = [] } = config

      let files = fs.readdirSync(root)
      //ignore目录中的文件忽略不做检查
      files = files.filter((file) => !ignores.includes(file))

      if (Array.isArray(includes) && includes.length > 0) {
        const otherFiles = files.filter((file) => !includes.includes(file))
        const hasOtherFile = otherFiles.length > 0

        if (hasOtherFile) {
          context.report({
            message: `${root}目录下只能包含 "${includes.join(
              '、',
            )}" 等文件夹，出现了意外的文件${otherFiles.join('、')}。`,
            loc: { line: 1, column: 0 },
          })
        } else {
          const missFiles = includes.filter((file) => !files.includes(file))
          if (missFiles.length > 0) {
            context.report({
              message: `${root}目录下缺少 "${missFiles.join(
                '、',
              )}" 等文件或者文件夹。`,
              loc: { line: 1, column: 0 },
            })
          }
        }
      }
    }

    return {
      Program() {
        options.forEach((config) => {
          checkSrcDirectory(config)
        })
      },
    }
  },
}
